package com.tyc.springframework.jvm.gc;

import java.util.concurrent.TimeUnit;

/**
 * 对象在GC时通过finalize方法自救
 * finalize方法只会被调用一次
 */
public class FinalizeEscapeGc {
    public static FinalizeEscapeGc obj = null;

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        FinalizeEscapeGc.obj = this;
    }

    public static void main(String[] args) throws InterruptedException {
        obj = new FinalizeEscapeGc();

        //第一次拯救自己
        obj = null;
        System.gc();
        TimeUnit.NANOSECONDS.sleep(500);
        if(obj == null){
            System.out.println("对象死亡");
        }else {
            System.out.println("对象存活");
        }

        //第二次不会在调用finalize方法
        obj = null;
        System.gc();
        TimeUnit.NANOSECONDS.sleep(500);
        if(obj == null){
            System.out.println("对象死亡");
        }else {
            System.out.println("对象存活");
        }
    }
}
